package net.chasing.androidbaseconfig.util.html;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.Html;
import android.text.TextUtils;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;

import net.chasing.androidbaseconfig.util.glide.ImageLoadUtils;

public class MyImageGetter implements Html.ImageGetter {

    private Context mContext;
    private TextView mTextView;

    public MyImageGetter(Context context, TextView textView) {
        mContext = context;
        mTextView = textView;
    }

    @Override
    public Drawable getDrawable(String source) {
        if (TextUtils.isEmpty(source) || source.startsWith("blob")) {
            return null;
        }

        URLDrawable urlDrawable = new URLDrawable();
        ImageLoadUtils.preloadDrawable(mContext, source, new RequestListener<Drawable>() {
            @Override
            public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                Drawable errorDrawable = ContextCompat.getDrawable(mContext, net.chasing.androidbaseconfig.R.mipmap.default_pic);
                if (errorDrawable != null) {
                    urlDrawable.setBounds(0, 0, errorDrawable.getIntrinsicWidth(), errorDrawable.getIntrinsicHeight());
                    urlDrawable.setDrawable(errorDrawable);
                    mTextView.invalidate();
                }
                return false;
            }

            @Override
            public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                urlDrawable.setDrawable(resource);
                urlDrawable.setBounds(0, 0, resource.getIntrinsicWidth(), resource.getIntrinsicWidth());
                mTextView.invalidate();
                mTextView.setText(mTextView.getText());
                return false;
            }
        });

        return urlDrawable;
    }
}
